<template>
	<section>

		<el-col :span="24" class="toolbar"  style="padding-bottom: 0px;">
			<el-form :inline="true">
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增用户</el-button>
				</el-form-item>		
				<el-form-item>
				  <el-select v-model="role" placeholder="请选择用户类型">			  	
				    <el-option value=""  label="全部" >
				    </el-option> 				  	
				    <el-option value="admin"  label="超级管理员" >
				    </el-option> 
				    <el-option value="manager"  label="学院管理员" >
				    </el-option> 
				    <el-option value="teacher"  label="学院老师" >
				    </el-option> 	
				    <el-option value="student"  label="学院学生" >
				    </el-option> 					    
				  </el-select>					
				</el-form-item>						
				<el-form-item>
					<el-input v-model="key"  placeholder="输入查询的关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="getList">查询</el-button>
				</el-form-item>
			</el-form>
		</el-col>					
		<!--工具条-->		
		<el-table :data="Lists" highlight-current-row v-loading="loading" style="width: 100%">
			<el-table-column  type="index" width='80'>
			</el-table-column>
			<el-table-column prop="realName" label="真实姓名" width="200">
			</el-table-column>			
			<el-table-column prop="orgName" label="所属机构"  width="200">
			</el-table-column>			
			<el-table-column prop="idCard" min-width="100" label="身份证号"  width="200">
			</el-table-column>		
			<el-table-column prop="phone" label="联系电话"  width="200">
			</el-table-column>				
			<el-table-column prop="mail" label="邮箱"  width="200">
			</el-table-column>
			<el-table-column prop="phone" label="手机号" width="200">
			</el-table-column>		
			<el-table-column prop="updateTime" label="创建时间" width="200">
			</el-table-column>			
			<el-table-column prop="birth" min-width="200" label="操作" fixed="right" sortable>
				<template scope="scope">
					<el-button size="small" type="danger" @click="handleDel(scope.row)">删除</el-button>
					<el-button size="small" type="primary" @click="getone(scope.row)">编辑</el-button>
					<el-button size="small" type="warning" v-if="!scope.row.isLocked">禁用</el-button>
					<el-button size="small" type="success" v-if="scope.row.isLocked">启用</el-button>
				</template>					
			</el-table-column>
		</el-table>
		<!--工具-->
		<el-col :span="24" class="toolbar">
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="10" :total="total" style="float:right;">
			</el-pagination>
		</el-col>		
		<!--新增界面-->
		<el-dialog  title="添加用户" :fullscreen="false" custom-class="userdialog"  v-model="addFormVisible" :close-on-click-modal="false">
			<el-form :model="adduser"  :rules="adduserrule" ref="adduser">		
				<el-form-item label="添加方式">
				    <el-radio-group v-model="adduser.way">
				      <el-radio label="1">手动添加</el-radio>
				      <el-radio label="2">批量导入</el-radio>
				    </el-radio-group>
				</el-form-item>		
				<template v-if="adduser.way==1">				
					<el-form-item label="手机号"  prop="phone" >
						<el-input v-model="adduser.phone" placeholder="填写手机号"  auto-complete="off"  style="width:40%;"></el-input>
					</el-form-item>	
					<el-form-item label="用户角色"  prop="role" >
					    <el-radio-group v-model="adduser.role">
					      <el-radio label="manager">学园管理员</el-radio>
					      <el-radio label="teacher">学园老师</el-radio>
					      <el-radio label="student">学园学生</el-radio>
					    </el-radio-group>
					</el-form-item>	
					<el-form-item label="性别"  prop="sex" >
					    <el-radio-group v-model="adduser.sex">
					      <el-radio label="1">男</el-radio>
					      <el-radio label="2">女</el-radio>
					    </el-radio-group>
					</el-form-item>		
					<el-form-item label="所属机构"  prop="orgId" v-if="$store.state.role=='admin'">
					    <el-select placeholder="请选择所属机构" v-model="adduser.orgId">
					      <el-option v-for="el in orgList" :value="JSON.stringify(el.orgId)" :label="el.name"></el-option>
					    </el-select>
					</el-form-item>					
					<el-form-item label="真实姓名"  prop="realName" >
						<el-input v-model="adduser.realName" placeholder="填写真实姓名"  auto-complete="off"  style="width:40%;"></el-input>
					</el-form-item>		
				
					<el-form-item label="身份证号码" prop="idCard">
						<el-input v-model="adduser.idCard" placeholder="填写真实身份证号码"  auto-complete="off"  style="width: 60%;"></el-input>
					</el-form-item>	
					<el-form-item label="邮箱">
						<el-input v-model="adduser.mail" placeholder="填写邮箱"  auto-complete="off"  style="width: 60%;"></el-input>
					</el-form-item>				
					<el-form-item label="住址">
						<el-input v-model="adduser.location" placeholder="填写现住址"  auto-complete="off"  style="width: 60%;"></el-input>
					</el-form-item>	
				</template>
				<template v-if="adduser.way==2">
					<el-form-item label="用户角色"  prop="role" >
					    <el-radio-group v-model="adduser.role">
					      <el-radio label="manager">学园管理员</el-radio>
					      <el-radio label="teacher">学园老师</el-radio>
					      <el-radio label="student">学园学生</el-radio>
					    </el-radio-group>
					</el-form-item>		
					<el-form-item label="所属机构"  prop="orgId">
					    <el-select placeholder="请选择所属机构" v-model="adduser.orgId">
					      <el-option v-for="el in orgList" :value="JSON.stringify(el.orgId)" :label="el.name"></el-option>
					    </el-select>
					</el-form-item>							
				    <el-form-item label="上传文件">
						<el-upload
						  class="upload-demo"
						  drag
						  action="cc"
						  :before-upload="beforeupload"
						  :file-list="fileList"
						  limit='1'
						  accept="xls/*">
						  <i class="el-icon-upload"></i>
						  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
						  <div class="el-upload__tip" slot="tip">只能上传xlx文件</div>
						</el-upload>
				    </el-form-item>	
				    <el-form-item label="文件模板">
				    	<a href="./static/img/用户模板.xls">
				    	<el-tag type="success">
						 	 点击下载文件模板
						</el-tag>
				    	</a>
				    </el-form-item>
				</template>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
		<!--编辑界面-->
		<el-dialog  title="编辑用户" :fullscreen="false" custom-class="userdialog"  v-model="editFormVisible" :close-on-click-modal="false">
			<el-form :model="edituser"  :rules="edituserrule" ref="edituser">		
				<el-form-item label="手机号"  prop="phone" >
					<el-input v-model="edituser.phone" placeholder="填写手机号"  auto-complete="off"  style="width:40%;"></el-input>
				</el-form-item>
				<el-form-item label="用户角色"  prop="role" >
				    <el-radio-group v-model="edituser.role">
				      <el-radio label="manager">学园管理员</el-radio>
				      <el-radio label="teacher">学园老师</el-radio>
				      <el-radio label="student">学园学生</el-radio>
				    </el-radio-group>
				</el-form-item>	
				<el-form-item label="所属机构"  prop="orgId" >
				    <el-select placeholder="请选择机构类型" v-model="edituser.orgId">
				      <el-option v-for="el in orgList" :value="el.orgId" :label="el.name"></el-option>
				    </el-select>
				</el-form-item>						
				<el-form-item label="性别"  prop="sex" >
				    <el-radio-group v-model="edituser.sex">
				      <el-radio label="1">男</el-radio>
				      <el-radio label="2">女</el-radio>
				    </el-radio-group>
				</el-form-item>		
				<el-form-item label="真实姓名"  prop="realName" >
					<el-input v-model="edituser.realName" placeholder="填写真实姓名"  auto-complete="off"  style="width:40%;"></el-input>
				</el-form-item>		
					
				<el-form-item label="身份证号码" prop="idCard">
					<el-input v-model="edituser.idCard" placeholder="填写真实身份证号码"  auto-complete="off"  style="width: 60%;"></el-input>
				</el-form-item>	
				<el-form-item label="邮箱">
					<el-input v-model="edituser.mail" placeholder="填写邮箱"  auto-complete="off"  style="width: 60%;"></el-input>
				</el-form-item>				
				<el-form-item label="住址">
					<el-input v-model="edituser.location" placeholder="填写现住址"  auto-complete="off"  style="width: 60%;"></el-input>
				</el-form-item>						
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>
<script>
	import { orglist,userlist,userdelete,useradd,userone,useredit,usernamerule,userTypelist,usermoreadd} from '../../api/api';

	//import NProgress from 'nprogress'
	export default {
		data() {
			var phonerule=(rule, value, callback)=>{
	  			var myreg=/^[1][3,6,4,5,7,8][0-9]{9}$/;
	            if (!myreg.test(value)) {
	                 callback(new Error('请填写有效手机号'))
	            } else {
	                callback()
	            }	  
			}		
			var idcardrule=(rule, value, callback)=>{
	  			var myreg=/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/; 
	            if (!myreg.test(value)) {
	                 callback(new Error('请填写真实身份证'))
	            } else {
	                callback()
	            }	  
			}				
			var realnamerule=(rule, value, callback)=>{
	  			var myreg=/^[\u4e00-\u9fa5]{2,4}$/;
	            if (!myreg.test(value)) {
	                 callback(new Error('请填写真实姓名'))
	            } else {
	                callback()
	            }	  
			}				
			var rulesname=(rules,value,callback)=>{
				console.log(value)
				let params={username:this.adduser.username};
				usernamerule(params).then((r)=>{
					if(!r){
						callback(new Error('用户名称重复'))
					}else{
						callback()
					}
				})
			}	
			var editrulesname=(rules,value,callback)=>{
				if(this.edituser.checkname!=this.edituser.username){			
					let params={username:this.edituser.username};
					usernamerule(params).then((r)=>{
						if(!r){
							callback(new Error('用户名称重复'))
						}else{
							callback()
						}
					})
				}else{
					callback()
				}
			}	
			var rulesphone=(rules,value,callback)=>{
				console.log(value)
				let params={phone:this.adduser.phone};
				usernamerule(params).then((r)=>{
					if(!r){
						callback(new Error('手机号重复'))
					}else{
						callback()
					}
				})
			}	
			var editrulesphone=(rules,value,callback)=>{
				if(this.edituser.checkphone!=this.edituser.phone){			
					let params={phone:this.edituser.phone};
					usernamerule(params).then((r)=>{
						if(!r){
							callback(new Error('手机号重复'))
						}else{
							callback()
						}
					})
				}else{
					callback()
				}
			}			
			return {
				addFormVisible: false,
				addLoading: false,	
				autouser:false,
				editFormVisible: false,
				editLoading: false,		
				userupload:"user",
				Lists:[],
				orgList:[],
				userTypeList:[],
				userTypeId:"",
				role:"",
				adduser:{
					username:"",
					intro:"",
					role:"",
					sex:"",
					realName:"",
					idCard:"",
					location:"",
					phone:"",
					mail:"",
					way:"1",
					orgId:""				
				},
				edituser:{
				
				},
				fileList:[],
				param:"",
				editparam:"",
				adduserrule: {
					username: [
						{ required: true, message: '填写用户名称', trigger: 'blur' },
						{validator:rulesname,trigger: 'blur'}	
					],
					role:[
						{ required: true, message: '角色类型不能为空', trigger: 'blur' },
					],	
					orgId:[
						{ required: true, message: '所属机构不能为空', trigger: 'blur' },
					],						
					phone:[
						{ required: true, message: '手机号不能为空', trigger: 'blur' },
						{ validator:phonerule,trigger: 'blur'},
						{validator:rulesphone,trigger: 'blur'}	
					],
					sex:[
						{ required: true, message: '性别不能为空', trigger: 'blur' },
					],
					realName:[
						{ required: true, message: '真实姓名不能为空', trigger: 'blur' },
						{validator:realnamerule,trigger: 'blur'}
					],
					idCard:[
						{ required: true, message: '身份证号码不能为空', trigger: 'blur' },
						{validator:idcardrule,trigger: 'blur'}
					],					
				},		
				edituserrule: {
					username: [
						{ required: true, message: '填写用户名称', trigger: 'blur' },
						{validator:editrulesname,trigger: 'blur'}	
					],
					orgId:[
						{ required: true, message: '所属机构不能为空', trigger: 'blur' },
					],						
					role:[
						{ required: true, message: '角色类型不能为空', trigger: 'blur' },
					],					
					phone:[
						{ required: true, message: '手机号不能为空', trigger: 'blur' },
						{ validator:phonerule,trigger: 'blur'},
						{validator:editrulesphone,trigger: 'blur'}	
					],
					sex:[
						{ required: true, message: '性别不能为空', trigger: 'blur' },
					],
					realName:[
						{ required: true, message: '真实姓名不能为空', trigger: 'blur' },
						{validator:editrulesname,trigger: 'blur'}
					],
					idCard:[
						{ required: true, message: '身份证号码不能为空', trigger: 'blur' },
						{validator:idcardrule,trigger: 'blur'}
					],
				},						
				form:{
					resource:""
				},
				page:"1",
				pagesize:"10",
				total:'',
				key:"",
				isShared:" ",
				isSelf:'1',
			}
		},
		watch:{
			
		},
		methods: {	
            beforeupload(file) {
                //创建临时的路径来展示图片
                var windowURL = window.URL || window.webkitURL;
                var planname=file.name;
                let oneplan={name:planname,url:''};
                this.fileList=[];
                this.fileList.push(oneplan);
                //重新写一个表单上传的方法
                this.param = new FormData();
                this.param.append('file', file, file.name);
                return false;
            },				
			goShared:function(row,type){
				this.$confirm('确定禁用此用吗?', '提示', {
			        confirmButtonText: '确定',
			        cancelButtonText: '取消',					
					type: 'warning'
				}).then(() => {
					var params=new FormData();
					params.append('isLocked',type);
					params.append('userId',row.userId);
					videoedit(params).then((r) => {
						if(!r.error){
							this.$message({
								message: '共享成功',
								type: 'success'
							});
							this.getList();									
						}else{
							this.$message({
								message: '共享失败',
								type: 'error'
							});						
						}
					})	
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '取消共享'		
					});						
				});				
			
			},
			handleAdd: function () {
				this.addFormVisible = true;
			},
			fileclick:function(){
				$('.userauto').toggle()
			},
			isSharedclick:function(type){
				this.isShared=type;
				this.getList();
			},
			//获取项目列表
			getorgList: function () {
				let params={pageNum:1,pageSize:100};
				orglist(params).then((res) => {
					this.orgList=res.list;
				});					
			},		
			//获取项目列表
			getList: function () {
				this.loading = true;
				//NProgress.start();
				let params={pageNum:this.page,pageSize:this.pagesize,key:this.key,role:this.role};
				userlist(params).then((res) => {
					this.total=res.total;					
					this.Lists = res.list;
					this.loading = false;
					//NProgress.done();
				});					
			},		
			getone:function(row){
				var params=row.userId;
				userone(params).then((res)=>{	
					res.checkname=res.username;
					res.checkphone=res.phone;
					res.orgId=JSON.stringify(res.orgId);
					this.editFormVisible=true;
					res.sex=JSON.stringify(res.sex);
					this.edituser = Object.assign({}, res);
				})
				
			},
			handleCurrentChange(val) {
				this.page = val;
				this.getList();
			},	       
			handleDel:function (row) {
				this.$confirm('确认删除该记录吗?', '提示', {
			        confirmButtonText: '确定',
			        cancelButtonText: '取消',					
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para =row.userId;
					userdelete(para).then((res) => {
						if(!res.error){
							this.listLoading = false;
							//NProgress.done();
							this.$message({
								message: '删除成功',
								type: 'success'
							});
							this.getList();							
						}else{
							this.$message({
								type: 'error',
								message: '取消失败'		
							});								
						}
					});
				}).catch(() => {
					this.$message({
						type: 'error',
						message: '取消失败'			
					});						
				});
			},
			//新增
			addSubmit: function () {
				if(this.adduser.way==1){
					this.param=new URLSearchParams()
					this.param.append('role',this.adduser.role);
					this.param.append('orgId',this.adduser.orgId);
					this.param.append('sex',this.adduser.sex);
					this.param.append('realName',this.adduser.realName);
					this.param.append('idCard',this.adduser.idCard);
					this.param.append('location',this.adduser.location);
					this.param.append('mail',this.adduser.mail);
					this.param.append('phone',this.adduser.phone);							
					this.$refs.adduser.validate((valid) => {
						if (valid) {
							this.$confirm('确认提交吗？', '提示', {}).then(() => {
								this.addLoading = true;
								//NProgress.start();						
	
								useradd(this.param).then((r) => {
									if(!r.error){
										this.addLoading = false;
										this.$message({
											message: '添加成功',
											type: 'success'
										});
										this.fileList=[];
										this.$refs['adduser'].resetFields();
										this.addFormVisible = false;
										this.param='';
										this.getList();									
									}else{
										this.addLoading = false;
										this.param='';
										this.$message({
											message: '添加失败',
											type: 'error'
										});										
									}
								}).catch(()=>{
									this.addLoading = false;
									this.param='';
									this.$message({
										message: '添加失败',
										type: 'error'
									});								
								});
							});
						}
					});					
				}else{
					if(this.fileList.length==0){
						this.$message({
							message: '文件不能为空',
							type: 'error'
						});				
						return;
					}
					this.param.append('role',this.adduser.role);
					this.param.append('orgId',this.adduser.orgId);					
					this.$refs.adduser.validate((valid) => {
						if (valid) {
							this.$confirm('确认提交吗？', '提示', {}).then(() => {
								this.addLoading = true;
								//NProgress.start();						
								usermoreadd(this.param).then((r) => {
									if(!r.error){
										this.addLoading = false;
										this.$message({
											message: '添加成功',
											type: 'success'
										});
										this.fileList=[];
										this.$refs['adduser'].resetFields();
										this.addFormVisible = false;
										this.param='';
										this.getList();									
									}else{
										this.addLoading = false;
										this.param='';
										this.$message({
											message: '添加失败',
											type: 'error'
										});										
									}
								})
							});
						}
					});					
				}
			},
			moreaddSubmit: function () {

			},			
			//编辑
			editSubmit: function () {
				this.editparam=new URLSearchParams()
				this.$refs.edituser.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							//NProgress.start();
							this.editparam.append('role',this.edituser.role);
							this.editparam.append('sex',this.edituser.sex);
							this.editparam.append('userId',this.edituser.userId);
							this.editparam.append('orgId',this.edituser.orgId);
							this.editparam.append('realName',this.edituser.realName);
							this.editparam.append('idCard',this.edituser.idCard);
							this.editparam.append('location',this.edituser.location);
							this.editparam.append('mail',this.edituser.mail);
							this.editparam.append('phone',this.edituser.phone);
							useredit(this.editparam).then((r) => {
								if(!r.error){
									this.editLoading = false;
									this.$message({
										message: '更新成功',
										type: 'success'
									});
									this.$refs['edituser'].resetFields();
									this.editFormVisible = false;
									this.eidtparam='',
									this.getList();									
								}else{
									this.editLoading = false;
									this.eidtparam='',
									this.$message({
										message: '更新失败',
										type: 'error'
									});										
								}
							}).catch(()=>{
								this.editLoading = false;
								this.eidtparam='',
								this.$message({
									message: '更新失败',
									type: 'error'
								});								
							});
						});
					}
				});
			},			
		},
		mounted() {
			this.getList();
			this.getorgList()
		}
	};

</script>

<style>
.userdialog {
	width:40%;
}
</style>